#include "relay_ctrl.h"
#include "elog.h"

/* 继电器端口初始化 */
int relay_ctrl_pin_init(void)
{
    rt_pin_mode(K1_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(K2_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(K3_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(K4_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(K1_PIN_DET, PIN_MODE_INPUT_PULLUP);
    rt_pin_mode(K2_PIN_DET, PIN_MODE_INPUT_PULLUP);
    log_d("relay pin init success.");
    return 0;
}
INIT_APP_EXPORT(relay_ctrl_pin_init);

/**
 * @brief                   继电器控制
 * @param  index            继电器编号
 * @param  level            0断开 1吸合
 * @return int              返回当前状态
 */
int relay_ctrl(int index, int level)
{
    int ret = 0;
    switch(index)
    {
        case RELAY_K1:
            rt_pin_write(K1_PIN, level);
            break;
        case RELAY_K2:
            rt_pin_write(K2_PIN, level);
            break;
        case RELAY_K3:
            rt_pin_write(K3_PIN, level);
            break;
        case RELAY_K4:
            rt_pin_write(K4_PIN, level);
            break;
        case RELAY_K5:
            rt_pin_write(K5_PIN, level);
            break;
        case RELAY_K6:
            rt_pin_write(K6_PIN, level);
            break;
        default:
            break;
    }
    return ret;
}

/**
 * @brief Get the relay status object
 * @return int 
 */
int get_relay_status(void)
{
    int ret = 0;

    if (!rt_pin_read(K1_PIN_DET))
    {
        ret |= (1 << 0);
    }

    if (!rt_pin_read(K2_PIN_DET))
    {
        ret |= (1 << 1);
    }
    return ret;
}
